<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/7
 * Time: 11:25
 */

namespace app\api\model;


class Behavior extends BaseModel
{
    protected $autoWriteTimestamp = true;
    protected $updateTime   = false;
    protected $rule =  array('type' => 'mod','num' =>4);//分表规则
        /**
         * 与behavior_type一对一关联
         * @return \think\model\relation\BelongsTo
         */
        public function type(){
            return $this->belongsTo('BehaviorType','type','id');
        }

    /**
     * 与user表一对一对应
     * @return \think\model\relation\BelongsTo
     */
        public function userInfo(){
            return $this->belongsTo('User','user_id','id');
        }

    /**
     * 与work_user多对一
     * @return \think\model\relation\BelongsTo
     */
        public function workUser(){
            return $this->belongsTo('WorkUser','wu_id','id');
        }

    /**
     * 创建行为
     * @param $data
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
        public function createBehavior($data){
            //获取查询次数
            $count =  self::where('type' ,'=',$data['type'])
                        ->partition(['user_id'=>$data['user_id']],'user_id',$this->rule)
                        ->where('user_id','=',$data['user_id'])
                        ->where('wu_id','=',$data['wu_id'])
                        ->count();
            $data['times'] = $count+1;
            $data['add_time'] = time();
            $id = (new Behavior())->partition($data,'user_id',$this->rule)->insert($data,'',true);
            return (new Behavior())->partition(['user_id'=>$data['user_id']],'user_id',$this->rule)->where('id','=',$id)->find();
        }

    /**
     * 获取行为列表
     * @param $wu_id
     * @param $page
     * @param $size
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
        public function getBehaviorList($wu_id,$page,$size){
            $list = self::with(['userInfo'])
                    ->partition([],'user_id',$this->rule)
                    ->where('wu_id','=',$wu_id)
                    ->field("user_id,content,type,times,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i') minute")
                    ->order('minute desc')
                    ->limit(($page-1)*$size,$size)
                    ->select();
            if (!$list->isEmpty()){
                foreach ($list as $value ){
                    $value->user_info->visible(['id','nickname','avatar_url']);
                }
            }
            return $list;
        }

    /**
     * 获取个人行为
     * @param $wu_id
     * @param $user_id
     * @param $page
     * @param $size
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
        public function getBehaviorListByUser($wu_id,$user_id,$page,$size){
            $list = self::with(['userInfo'])
                ->partition([['user_id'=>$user_id]],'user_id',$this->rule)
                ->where('wu_id','=',$wu_id)
                ->where('user_id','=',$user_id)
                ->field("user_id,content,type,times,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i') minute")
                ->order('minute desc')
                ->limit(($page-1)*$size,$size)
                ->select();
            if (!$list->isEmpty()){
                foreach ($list as $value ){
                    $value->user_info->visible(['id','nickname','avatar_url']);
                }
            }
            return $list;
        }
    /**
     * 根据分类获取行为列表
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getBehaviorListByCategory($wu_id,$type,$time,$page,$size){
        $list = self::with(['userInfo'])
            ->partition([],'user_id',$this->rule)
            ->where('wu_id','=',$wu_id)
            ->where('type','=',$type)
            ->where('add_time','>',$time['start'])
            ->where('add_time','<',$time['end'])
            ->field('count(id),user_id,type,max(times)')
            ->group('user_id')
            ->limit(($page-1)*$size,$size)
            ->select();
        if (!$list->isEmpty()){
            foreach ($list as $value ){
                $info = $value->visible(['count(id)','type','user_info','max(times)']);
                $info->user_info->visible(['id','nickname','avatar_url']);
            }
        }
        return $list;
    }

    /**
     * 获取行为统计数量
     * @param $type
     * @param $wu_id
     * @return int|string
     */
    public function getBehaviorByType($type,$wu_id,$time){
        $num = self::where('wu_id','=',$wu_id)
            ->with(['type'])
            ->partition([],'user_id',$this->rule)
            ->where('add_time','>',$time['start'])
            ->where('add_time','<',$time['end'])
            ->where('type','in',$type)
            ->field('type,count(behavior_id)')
            ->group('type')
            ->select();
        return $num;
    }

    /**
     * 根据客户id获取行为列表
     * @param $uid
     * @param $time
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getBehaviorByUid($uid,$time){
        $result = self::where('user_id','=',$uid)
            ->partition([['user_id'=>$uid]],'user_id',$this->rule)
            ->where('add_time','>',$time['start'])
            ->where('add_time','<',$time['end'])
            ->join('behavior_type u','type = u.id')
            ->field('u.name,u.pub_name,type,count(content) num')
            ->group('type')
            ->select();
        return $result;
    }

    /**
     * 获取最近活动用户
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUid($wu_id){
        $result = self::where("wu_id",'=',$wu_id)
            ->partition([],'user_id',$this->rule)
            ->field('user_id,max(add_time) add_time')
            ->group('user_id')
            ->order('add_time desc')
            ->with(['userInfo'])
            ->select();
      foreach ($result as $value){
          if (!empty($value->user_info)){
              $value->user_info->visible(['id','nickname','avatar_url']);
          }
      }
        return $result;
    }

    /**
     * 获取行为用户
     * @param $wu_id
     * @param $page
     * @param $size
     * @return \think\Paginator
     */
    public static function getBehaviorUser($wu_id,$page,$size){
        $result = self::where("wu_id",'=',$wu_id)
            ->partition([],'user_id',array('type' => 'mod','num' =>4))
            ->field('user_id,max(add_time) add_time')
            ->group('user_id')
            ->order('add_time desc')
            ->with(['userInfo'])
           ->paginate($size,false,['page'=>$page]);
        foreach ($result as $value){
            if (!empty($value->user_info)){
                $value->user_info->visible(['id','nickname','avatar_url']);
            }
        }
        return $result;
    }


    /**
     * 行为类型数量
     * @return int|string
     */
    public function getBehaviorData($uid,$wu_id){
        $result = self::where("user_id",'=',$uid)
            ->where('wu_id','=',$wu_id)
            ->partition([['user_id'=>$uid]],'user_id',$this->rule)
            ->join('behavior_type u','type = u.id')
            ->group('u.class')
            ->field('u.class,count(content) num')
            ->select();
        return $result;
    }
    /**
     * 活跃度数量统计
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getActiveData($user_id,$wu_id,$time){
        $result = self::where('user_id','=',$user_id)
            ->where('wu_id','=',$wu_id)
            ->where('add_time',">=",$time)
            ->partition([['user_id'=>$user_id]],'user_id',$this->rule)
            ->field("FROM_UNIXTIME(add_time,'%m-%d') days,count(content) num")
            ->group('days')
            ->select();
        return $result;
    }

    /**
     * 互动统计
     * @param $user_id
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInteractionData($user_id,$wu_id){
        $result = self::where('user_id','=',$user_id)
            ->where('wu_id','=',$wu_id)
            ->partition([['user_id'=>$user_id]],'user_id',$this->rule)
            ->join('behavior_type u','type = u.id')
            ->where("u.class = 1")
            ->field("u.name,u.pub_name,count(content) num")
            ->group('type')
            ->select();
        return $result;
    }

    /**
     * 浏览量统计
     * @param $t_id
     * @return int|string
     */
    public  function getBrowseData($t_id,$type,$time)
    {
        $type = BehaviorType::where('pub_name', '=', $type)->value('id');
        $work_user = WorkUser::where('t_id', '=', $t_id)->column('id');
        $result = self::where('type', '=', $type)
            ->where('wu_id', 'in', $work_user)
            ->partition([], 'user_id', $this->rule)
            ->where('add_time', '>', $time)
            ->count();
        return $result;
    }

    /**
     * 根据时间获取行为统计量
     * @param $t_id
     * @param $type
     * @param $time
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBrowseDataByTime($t_id,$type,$time){
        $type = BehaviorType::where('pub_name', '=', $type)->value('id');
        $work_user = WorkUser::where('t_id', '=', $t_id)->column('id');
        $result = self::where('type', '=', $type)
            ->where('wu_id', 'in', $work_user)
            ->partition([], 'user_id', $this->rule)
            ->where('add_time', '>', $time)
            ->field("FROM_UNIXTIME(add_time,'%m-%d') days,count(id) num")
            ->group('days')
            ->select();
        return $result;
    }

    /**
     * 行为类型数量
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllBehaviorData($t_id){
        $work_user = WorkUser::where('t_id','=',$t_id)->column('id');
        $result = self::where('wu_id','in',$work_user)
            ->partition([],'user_id',$this->rule)
            ->join('behavior_type u','type = u.id')
            ->group('u.class')
            ->field('u.class,count(content) num')
            ->select();
        return $result;
    }

    /**
     * 所有活跃度统计
     * @param $t_id
     * @param $time
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllActiveData($t_id,$time){
        $work_user = WorkUser::where('t_id','=',$t_id)->column('id');
        $result = self::where('wu_id','in',$work_user)
            ->where('add_time',">=",$time)
            ->partition([],'user_id',$this->rule)
            ->field("FROM_UNIXTIME(add_time,'%m-%d') days,count(content) num")
            ->group('days')
            ->select();
        return $result;
    }

    /**
     * 获取总互动统计
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllInteractionData($t_id){
        $work_user = WorkUser::where('t_id','=',$t_id)->column('id');
        $result = self::where('wu_id','in',$work_user)
            ->partition([],'user_id',$this->rule)
            ->join('behavior_type u','type = u.id')
            ->where("u.class = 1")
            ->field("u.name,u.pub_name,count(content) num")
            ->group('type')
            ->select();
        return $result;
    }

}